﻿using System;
using DAL.POCO;
using DAL.Repositories;

namespace GameAdmin.Pages
{
    public partial class question : System.Web.UI.Page
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            btnSave.Click += new EventHandler(btnSave_Click);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (RouteData.Values["id"] != null)
                {
                    LoadOriginalValues();
                }
            }
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    Question q = new Question();
                    q.lvl = Int32.Parse(ddlDifficulties.SelectedValue);
                    q.text = txtText.Text;

                    if (txtId.Text == "") QuestionRepository.Insert(q);
                    else
                    {
                        q.id = Int32.Parse(txtId.Text);
                        QuestionRepository.Update(q);
                    }

                    Response.Redirect("~/questions", true);
                }
                catch (Exception ex)
                {
                    lblMessage.Visible = true;
                    lblMessage.Text = ex.Message;
                }
            }
        }

        private void LoadOriginalValues()
        {
            int id = Int32.Parse((string)RouteData.Values["id"]);

            Question q = QuestionRepository.GetQuestion(id);

            txtId.Text = id.ToString();
            ddlDifficulties.SelectedValue = q.lvl.ToString();
            txtText.Text = q.text;
        }
    }
}